package com.adjaisd.scarecrow.controller;

import com.adjaisd.scarecrow.common.result.Result;
import com.adjaisd.scarecrow.common.utils.jwt.JwtUtils;
import com.adjaisd.scarecrow.entity.Device;
import com.adjaisd.scarecrow.entity.Panel;
import com.adjaisd.scarecrow.entity.Quota;
import com.adjaisd.scarecrow.service.*;
import com.adjaisd.scarecrow.vo.*;
import com.google.common.base.Strings;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author adjaisd
 * @since 2022-04-23
 */
@RestController
@RequestMapping("/panel")
public class PanelController {

    @Autowired
    DeviceService deviceService;

    @Autowired
    QuotaService quotaService;

    @Autowired
    PanelService panelService;

    @ApiOperation(value = "添加面板")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Result addPanel(HttpServletRequest request, @RequestBody Map<String, String> panelForm) {
        String token = request.getHeader("X-token");
        Claims claims = JwtUtils.getMembers(token);
        Long userId = Long.parseLong(claims.get("id").toString());

        try {
            String name = panelForm.get("name");
            Long deviceId = Long.valueOf(panelForm.get("deviceId"));
            Long quotaId = Long.valueOf(panelForm.get("quotaId"));

            Long time = new Date().getTime();
            // 检查是否存在设备
            Device device = deviceService.getDeviceByID(deviceId);
            if (device == null || !device.getOwnerId().equals(userId))
                return Result.fail().code(400).message("不存在该设备");
            // 检查是否存在指标
            Quota q = quotaService.getQuotaByID(quotaId, userId);
            if (q == null || q.getCreateTime() == 0L) //不存在指标ID
                return Result.fail().code(400).message("没有该指标");
            // 检查是否存在面板
            Panel p = panelService.getPanel(userId, name, deviceId, quotaId);
            if (p != null && p.getCreateDate() > 0L) return Result.fail().code(400).message("已定义该面板");
            panelService.addPanel(p);
            Panel panel = panelService.getPanel(userId, name, deviceId, quotaId);
            System.out.println("panel = " + panel.toString());
            return Result.succ().code(200).data("panel", panel).message("添加面板成功");
        } catch (Exception e) {
            System.out.println(e);
            return Result.fail().code(50015).message("缺少必要参数");
        }
    }

    @ApiOperation(value = "删除面板")
    @ApiImplicitParam(name = "panelForm", required = true, value = "面板信息表", paramType = "body", dataType = "json")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Result delPanel(HttpServletRequest request, @RequestBody Map<String, String> panelForm) {
        String token = request.getHeader("X-token");
        Claims claims = JwtUtils.getMembers(token);
        Long userId = Long.parseLong(claims.get("id").toString());

        try {
            String name = panelForm.get("name");
            Long deviceId = Long.valueOf(panelForm.get("deviceId"));
            Long quotaId = Long.valueOf(panelForm.get("quotaId"));

            Panel panel = panelService.getPanel(userId, name, deviceId, quotaId);
            if (panel == null) return Result.fail().code(400).message("不存在该面板");
            if (panelService.delPanel(userId, name, deviceId, quotaId)) {
                return Result.succ().code(200).message("删除成功");
            } else return Result.fail().code(400).message("删除失败");
        } catch (Exception e) {
            System.out.println(e);
            return Result.fail().code(50015).message("缺少必要参数");
        }
    }

    @Autowired
    DeviceStatusService deviceStatusService;

    // 添加面板中实现级联选择
    // user --> device 对应 queryDevicePage
    // device --> quota 对应 queryQuotaPage
    // 适用于预览只含有单个指标数据的面板
    // 通过新建面板分组表来将多个指标数据展示到一个图标中
    @ApiOperation(value = "influx分页查询设备")
    @ApiImplicitParam(name = "map", required = true, value = "分页信息表", paramType = "body", dataType = "json")
    @RequestMapping(value = "/device-page", method = RequestMethod.POST)
    @ResponseBody
    public Result queryDevicePage(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String token = request.getHeader("X-token");
        Claims claims = JwtUtils.getMembers(token);
        long userId = Long.parseLong(claims.get("id").toString());

        String number = "";
        long page = 1L, pageSize = 10L;
        try {
            if (map.containsKey("page")) page = Long.parseLong(map.get("page"));
            if (map.containsKey("pageSize")) pageSize = Long.parseLong(map.get("pageSize"));
            if (map.containsKey("number")) {
                number = map.get("number");
                Device device = deviceService.getDeviceByNumber(Long.valueOf(number));
                if (!device.getOwnerId().equals(userId))    // 检测是否拥有者
                    return Result.fail().code(400).message("没有该设备");
            }
            Pager<Device> pageResult = panelService.getDevicePage(userId, page, pageSize, number);
            return Result.succ().code(200).data("pager", pageResult).message("分页查询设备成功");
        } catch (Exception e) {
            System.out.println(e);
            return Result.fail().code(400).message("参数错误");
        }
    }

    @ApiOperation(value = "influx分页查询设备指标")
    @ApiImplicitParam(name = "map", required = true, value = "分页信息表", paramType = "body", dataType = "json")
    @RequestMapping(value = "/device-quota", method = RequestMethod.POST)
    @ResponseBody
    public Result queryQuotaPage(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String token = request.getHeader("X-token");
        Claims claims = JwtUtils.getMembers(token);
        long userId = Long.parseLong(claims.get("id").toString());

        long page = 1L, pageSize = 10L;
        try {
            if (map.containsKey("page")) page = Long.parseLong(map.get("page"));
            if (map.containsKey("pageSize")) pageSize = Long.parseLong(map.get("pageSize"));
            String number = map.get("number");
            Device device = deviceService.getDeviceByNumberUID(Long.valueOf(number), userId);
            if (device == null || device.getBindTime() == 0L)
                return Result.fail().code(400).message("不存在该设备");
            Pager<Quota> quotaPager = panelService.getQuotaPage(userId, page, pageSize, device.getId() + "");
            return Result.succ().code(200).data("pager", quotaPager).message("分页查询设备成功");
        } catch (Exception e) {
            System.out.println(e);
            return Result.fail().code(400).message("参数错误");
        }
    }

    // 一个图只展示一个指标数据
    @ApiOperation(value = "获取指标下接受到的历史数据")
    @ApiImplicitParam(name = "map", required = true, value = "查询信息表", paramType = "body", dataType = "json")
    @RequestMapping(value = "/quota-data", method = RequestMethod.POST)
    @ResponseBody
    public Result getQuotaData(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String token = request.getHeader("X-token");
        Claims claims = JwtUtils.getMembers(token);
        Long userId = Long.parseLong(claims.get("id").toString());

        int type = -1;
        String quotaId = "";
        try {
            String beg = map.get("beg");
            String end = map.get("end");
            String number = map.get("number");
            if (map.containsKey("quotaId")) quotaId = map.get("quotaId");
            if (map.containsKey("type")) type = Integer.parseInt(map.get("type"));
            // 检测是否拥有设备
            Device device = deviceService.getDeviceByNumberUID(Long.valueOf(number), userId);
            if (device == null || device.getBindTime() == 0L)
                return Result.fail().code(400).message("没有该设备");
            // 若限定指标，则检测是否拥有指标
            if (!Strings.isNullOrEmpty(quotaId)) {
                Quota quota = quotaService.getById(quotaId);
                if (quota == null || quota.getCreateTime() == 0L ||
                        !quota.getOwnerId().equals(userId))
                    return Result.fail().code(400).message("没有该指标");
            }
            List<QuotaDataVO> quotaDataList = panelService.getQuotaDataList(userId, device.getId() + "", quotaId, beg, end, type);
            return Result.succ().code(200).data("quotaDataList", quotaDataList).message("查询指标历史数据成功");
        } catch (Exception e) {
            System.out.println(e);
            return Result.fail().code(400).message("参数错误");
        }
    }

}
